package org.fglxy.mockserver.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import org.springframework.util.StringUtils;

public abstract class WebUtils {
	
	private static String[] IP_SRC_ARR = new String[] {
			"x-forwarded-for",
			"Proxy-Client-IP",
			"WL-Proxy-Client-IP",
			"HTTP_CLIENT_IP",
			"HTTP_X_FORWARDED_FOR",
			"X-Real-IP"
	};
	
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getRequestAttribute(String key) {
		return (T) WebUtils.getRequest().getAttribute(key);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getRequestParameter(String key) {
		return (T) WebUtils.getRequest().getParameter(key);
	}
	
	public static HttpSession getSession() {
		return WebUtils.getRequest().getSession();
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getSessionAttribute(String key) {
		return (T) WebUtils.getSession().getAttribute(key);
	}
	
	public static String getIpAddr() {
		HttpServletRequest request = getRequest();
        String ip = null;
        for (String ipSrc : IP_SRC_ARR) {
        	ip = request.getHeader(ipSrc); 
            if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) { 
            	return ip;
            }  
        }
        ip = request.getRemoteAddr();  
        if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {  
            return ip;
        } 
        return ip;  
    }

	public static String getReferer() {
		HttpServletRequest request = getRequest();
		return request.getHeader("referer");
	}

	public static String getRequestURL() {
		HttpServletRequest request = getRequest();
		return request.getRequestURL().toString();
	}

	public static String getBaseURL() {
		HttpServletRequest request = getRequest();
		StringBuilder builder = new StringBuilder();
		if (!StringUtils.isEmpty(request.getContextPath())) {
			builder.append("/").append(request.getContextPath());
		}
		builder.append("/");
		return builder.toString(); 
	}
}
